package br.ykhan.t5.ytools.menu.services;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ComponentClassResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.ykhan.t5.ytools.menu.beans.SiteMenu;
import br.ykhan.t5.ytools.menu.beans.SitePage;
import br.ykhan.t5.ytools.menu.utils.Utils;

public class DefaultMenuBuilder implements MenuBuilder
{
	@Inject private ComponentClassResolver 	componentClassResolver;
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public SiteMenu buildMenu(List<String> pagesURI)
	{
		// Organiza as URI's por Level e alfabeticamente
		Utils.sortPageNamesByLevel(pagesURI);
		
		Set<SitePage> pages = mapPages(pagesURI);
		
		// Menu Root do Site
		SiteMenu mainMenu = new SiteMenu();
		
		for(SitePage page : pages)
			mainMenu.addPage(page);
		
		return mainMenu;
	}
	
	/**
	 * Maps each Page Name to a {@link SitePage}
	 */
	private Set<SitePage> mapPages(List<String> pageNames)
	{
		Set<SitePage> pages = new LinkedHashSet<SitePage>();
		
		for(String pageName : pageNames)
			// Better safe than sorry..
			if (componentClassResolver.isPageName(pageName))
				try
				{
					pages.add(new SitePage(pageName, Class.forName(componentClassResolver.resolvePageNameToClassName(pageName))));
				}
				catch (ClassNotFoundException e)
				{
					logger.warn("Could not resolve Page Name '%s' to a Component Class", pageName);
				}
				
		return pages;
	}
}
